#!/usr/bin/env php
<?php
/**
 * This file is part of Swow
 *
 * @link     https://github.com/swow/swow
 * @contact  twosee <twosee@php.net>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code
 */

require_once __DIR__ . '/../tools.php';

use function Swow\Tools\askBool;
use function Swow\Tools\br;
use function Swow\Tools\error;
use function Swow\Tools\notice;
use function Swow\Tools\log;
use function Swow\Tools\ok;
use function Swow\Tools\success;
use function Swow\Tools\warn;
use function Swow\Tools\passthru;

if (PHP_OS_FAMILY === 'Windows') {
    error('Not supported on Windows temporarily');
}

$workSpace = realpath(__DIR__ . '/../../ext');

$swowSo = "{$workSpace}/.libs/swow.so";
$options = getopt('', ['sudo', 'install', 'rebuild', 'show-log', 'debug', 'thread-context', 'msan', 'asan', 'ubsan', 'enable::']);

$commandExecutor = function (string $name, array $commands) use ($workSpace): void {
    array_unshift($commands, "cd {$workSpace}");
    passthru(...$commands) && error("{$name} failed");
    ok("{$name} complete");
    br();
};

if (isset($options['rebuild'])) {
    $cleanCommands = [];
    if (file_exists("{$workSpace}/Makefile")) {
        $cleanCommands[] = './clean.sh';
    }
    $cleanCommands[] = 'phpize --clean';
    $commandExecutor('Clean', $cleanCommands);
}

$configureCommands = [];
if (!file_exists("{$workSpace}/configure") || isset($options['rebuild'])) {
    $configureCommands[] = 'phpize';
}
if (!file_exists("{$workSpace}/Makefile") || isset($options['rebuild'])) {
    $configureOptions = [];
    if (isset($options['debug'])) {
        $configureOptions[] = '--enable-swow-debug';
    }
    if (isset($options['thread-context'])) {
        $configureOptions[] = '--enable-swow-thread-context';
    }
    if (isset($options['msan'])) {
        $configureOptions[] = '--enable-swow-memory-sanitizer';
    }
    if (isset($options['asan'])) {
        $configureOptions[] = '--enable-swow-address-sanitizer';
    }
    if (isset($options['ubsan'])) {
        $configureOptions[] = '--enable-swow-undefined-sanitizer';
    }
    if (isset($options['enable'])) {
        $configureOptions[] = $options['enable'];
    }
    $configureOptions = implode(' ', $configureOptions);
    $configureCommands[] = "./configure {$configureOptions}";
}
$commandExecutor('Configure', $configureCommands);

// TODO: use Swow\Cpu module
$cpuCount = (int) `{$workSpace}/deps/libcat/tools/cpu_count.sh`;
if ($cpuCount <= 0) {
    $cpuCount = 4;
}
// TODO: CFLAGS/CXXFLAGS Werror
$makeCommand = "make -j{$cpuCount}";
if (!isset($options['show-log'])) {
    $makeCommand .= ' > /dev/null';
    notice('Please be patient while compiling in silent mode...');
}
$commandExecutor('Make', [$makeCommand]);

$checkCommand = "/usr/bin/env php -n -d extension={$swowSo} --ri swow";
ob_start();
$status = passthru($checkCommand);
$swowInfo = ob_get_clean();
if ($status === 0) {
    log($swowInfo);
} else {
    warn("Get extension info failed");
}

$expectInstall = isset($options['install']);
if (!$expectInstall) {
    $expectInstall = askBool('Do you want to install it right now?');
}
if ($expectInstall) {
    $haveSudo = getmyuid() !== 0;
    $expectSudo = isset($options['sudo']);
    if ($expectSudo && $haveSudo) {
        notice('Install the extension to your system requires root privileges');
        $sudo = 'sudo';
    } else {
        $sudo = '';
    }
    $commandExecutor('Install', ["{$sudo} make install"]);
}

success('All tasks have been completed');
